<template>
    <el-dialog :title="dialogTitle" :center="isCenter" v-model="innerDialogVisible" :show-close="false" :close-on-click-modal="false"
        @update:visible="updateVisible" :before-close="handleClose">
        <div class="container">
            <div class="drag-box">
                <draggable v-model="innerQuestionTypes" group="questionTypes" @end="updateOrder" class="drag-area">
                    <template #item="{ element, index }">
                        <div class="draggable-item">
                            <!-- <el-checkbox :label="element.type" v-model="innerQuestionTypes[index].selected">
                            {{ element.type }}
                        </el-checkbox> -->
                            <div class="singleItem">{{ element.type }}</div>
                        </div>
                    </template>
                </draggable>
            </div>
            <div v-if="galleryData!={}" class="gallery">
                <h2>旧题型顺序</h2>
                <div v-for="item in galleryData" :key="item">{{ item }}</div>
            </div>
        </div>
        <div class="dialog-footer">
            <el-button @click="cancelSelection">取消</el-button>
            <el-button type="primary" @click="confirmSelection">确定</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, computed, onMounted, watchEffect } from 'vue';
import draggable from 'vuedraggable';
import 'element-plus/theme-chalk/el-scrollbar.css';
import { submitQuestionTypesOrder, getQuestionTypesOrder } from '@/api/target_item_info_input';
const props = defineProps({
    editing: Boolean,
    questionTypes: Array,
    dialogVisible: Boolean,
    currentPaperType: String
});
const galleryData=ref([])
const emit = defineEmits(['update:dialogVisible']);
const innerDialogVisible = ref(props.dialogVisible);
const innerQuestionTypes = ref([]);
const currentPaperType = ref(props.currentPaperType)
const modifyID=ref(0)
const isCenter=ref(true)
// 添加重置 innerQuestionTypes 状态的方法
const resetInnerQuestionTypes = () => {
    innerQuestionTypes.value = props.questionTypes.map(x => ({ ...x }));
    getTypeOrder()
};
const getTypeOrder=async()=>{
    const res = await getQuestionTypesOrder(acs_id, currentPaperType.value)
    // console.log("res",res.data.data.order);
    console.log("galleryData.value", galleryData.value);
    if (res.data.data.order){
        galleryData.value = res.data.data.order
    }
    if (galleryData.value!=null){
        isCenter.value=false
    }
    modifyID.value = res.data.data.id
}
onMounted(async() => {
    resetInnerQuestionTypes(); // 初始加载时也应用重置，确保状态是最新的
    // getTypeOrder()
});
watch(() => props.questionTypes, (newVal) => {
    resetInnerQuestionTypes(); // 当父组件中的questionTypes更新时，同步更新本地状态
}, { deep: true });
watch(() => props.dialogVisible, (newVal) => {
    innerDialogVisible.value = newVal;
    if (!newVal) {
        resetInnerQuestionTypes(); // 对话框关闭时重置状态
    }
});
const updateVisible = (newVal) => {
    innerDialogVisible.value = newVal;
    emit('update:dialogVisible', newVal);
    if (!newVal) {
        resetInnerQuestionTypes(); // 确保在任何情况下关闭对话框时都重置状态
    }
};
const cancelSelection = () => {
    innerDialogVisible.value = false;
    emit('update:dialogVisible', false);
};
import { useRoute } from 'vue-router';
const route = useRoute();
const subId = parseInt(route.params.subId);
import { useClassStore } from '@/stores/modules/class'
const classStore = useClassStore()
const acs_id = classStore.classInfo.user_and_acs_id
// const confirmSelection = async () => {
//     const selectedQuestionTypes = innerQuestionTypes.value.filter(qt => qt.selected);
//     console.log('Selected Question Types', selectedQuestionTypes);
//     let orderObject = {};
//     let cnt = 1
//     innerQuestionTypes.value.forEach((qt, index) => {
//         if (qt.selected) {
//             orderObject[cnt++] = qt.type
//         }
//     });
//     const payload = {
//         type: currentPaperType.value,
//         order: orderObject,
//         subId
//     };
//     await submitQuestionTypesOrder(payload)
//     emit('update:dialogVisible', false);
// };
const confirmSelection = async () => {
    let orderObject = {};
    let cnt = 1;
    // 遍历所有题型，无论是否选中，都添加到orderObject中
    innerQuestionTypes.value.forEach((qt, index) => {
        orderObject[cnt++] = qt.type;
    });
    const payload = {
        type: currentPaperType.value,
        order: orderObject,
        id: modifyID.value
    };
    console.log("payload", payload);
    // 发送请求
    try {
        await submitQuestionTypesOrder(payload);

        // 关闭对话框
        emit('update:dialogVisible', false);
        ElMessage.success("题型编辑成功");
    } catch (error) {
        console.log("error",error);
    }

};

const dialogTitle = computed(() => {
    // return props.editing ? '编辑试卷题型顺序(点击并拖拽以调整顺序)' : '选择题型';
    return props.editing ? '上下拖拽以调整顺序' : '选择题型';
});
</script>

<style lang="scss" scoped>
.container{
    display: flex;
    justify-content: space-around;
    .drag-box{
        width: 40%;
        .drag-area {
                .draggable-item {
                    display: flex;
                    align-items: center;
                    padding: 0.5rem;
                    margin-bottom: 0.5rem;
                    background-color: #FFF;
                    border: 1px solid #ebebeb;
                    cursor: grab;
                    border-radius: 4px;
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                    text-align: center;
                    &:hover {
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
                    }
                    .singleItem{
                        width: 100%;
                        text-align: center;
                    }
                }
         }
    }
    .gallery {
        flex: 1;
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        margin-top: -70px;
            div {
                margin: 10px;
                width: 40%;
                text-align: center;
                padding: 10px;
                border: 1px solid #ccc;
                border-radius: 5px;
                background-color: #f2f2f2;
                box-shadow: 2px 2px 5px #888888;
            }
    }
}
.dialog-footer{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
}
</style>
